<?php
namespace App\Http\Controllers\MiniProgram;

use App\Http\Controllers\Controller;
use Carbon\Carbon;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;


class MiniProgramController extends Controller{

    protected $app_id;
    protected $app_secret;
    protected $options;

    public function __construct(){
        $this->app_id = env('MINIPROGRAM_APPID');
        $this->app_secret = env('MINIPROGRAM_APPSECRET');
        $this->options = [
            'mini_program' => [
                'app_id' => $this->app_id,
                'secret' => $this->app_secret,
            ],
        ];
    }

    /**
     * 通过code换取session_key和openid
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function codeToSession(Request $request){
        $validator = Validator::make($request->all(), [
            'code' => 'required',
        ], [
            'code.required' => '10001',
        ]);

        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        $app = new Application($this->options);
        $miniProgram = $app->mini_program;
        $res = $miniProgram->sns->getSessionKey($request['code']);

        if (!empty($res->openid)){
            return $this->sendSuccessResponse($res);
        }
        return $this->sendFailResponse(400, 40002);
    }

    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @return \Illuminate\Http\JsonResponse
     */
    public function decryptData(Request $request){
        $validator = Validator::make($request->all(), [
            'sessionKey' => 'required',
            'iv' => 'required',
            'encryptedData' => 'required',
        ], [
            'sessionKey.required' => '10001',
            'iv.required' => '10001',
            'encryptedData.required' => '10001',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        if (strlen($request['sessionKey']) != 24){
            return $this->sendFailResponse(400, 40108);
        }
        $aesKey=base64_decode($request['sessionKey']);
        if (strlen($request['iv']) != 24){
            return $this->sendFailResponse(400, 40109);
        }
        $aesIV=base64_decode($request['iv']);
        $aesCipher=base64_decode($request['encryptedData']);
        $result=openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj=json_decode($result);
        if( $dataObj  == NULL ) {
            return $this->sendFailResponse(400, 40110);
        }
        if( $dataObj->watermark->appid != $this->app_id ) {
            return $this->sendFailResponse(400, 40110);
        }
        return $this->sendSuccessResponse($dataObj);
    }

//    /**
//     * EasyWeChat解密数据（有BUG，返回Undefined index: token）
//     * @param Request $request
//     * @return \Illuminate\Http\JsonResponse
//     */
//    public function decryptData(Request $request){
//        $validator = Validator::make($request->all(), [
//            'sessionKey' => 'required',
//            'iv' => 'required',
//            'encryptedData' => 'required',
//        ], [
//            'sessionKey.required' => '10001',
//            'iv.required' => '10001',
//            'encryptedData.required' => '10001',
//        ]);
//
//        if ($validator->fails()) {
//            return $this->sendFailResponse(400, $validator->errors()->first());
//        }
//        $app = new Application($this->options);
//        $miniProgram = $app->mini_program;
//        $res = $miniProgram->encryptor->decryptData($request['sessionKey'], $request['iv'], $request['encryptedData']);
//
//        if (!empty($res->phoneNumber)){
//            return $this->sendSuccessResponse($res);
//        }
//        return $this->sendFailResponse(400, 40002);
//    }
}